package org.yejiali.handler.security;

import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.yejiali.common.enums.AppHttpCodeEnum;
import org.yejiali.common.response.ResponseResult;
import org.yejiali.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:yejiali
 * @Date:2025/2/20-02-20-18:42
 * @Decsription:org.yejiali.handler.security 认证失败
 * @Version:1.0
 */
@Component
public class AuthenticationEntrypointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //打印异常信息
        e.printStackTrace();
        //InsufficientAuthenticationException 未携带token抛出异常
        //BadCredentialsException 密码错误抛出异常
        ResponseResult responseResult = null;
        if (e instanceof BadCredentialsException) {
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), e.getMessage());
        } else if (e instanceof InsufficientAuthenticationException) {
            responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else{
            responseResult=ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证失败");
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(responseResult));
    }
}
